#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include "log.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

int main()
{
    //创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        LOG((int)LogLevel::FATAL) << "套接字创建失败，服务器退出!";
        exit(1);
    }
    uint16_t port = 8080;
    std::string ip = "192.168.8.16";

    //指定远端服务器的ip， port
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);
    memset(&peer, 0, sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(port);
    peer.sin_addr.s_addr = inet_addr(ip.c_str());
    InetAddr server(peer);

    while(true)
    {
        char sdMessage[1000];
        std::cin.getline(sdMessage, sizeof(sdMessage));
        int n = sendto(sockfd, sdMessage, sizeof(sdMessage), 0, (sockaddr*)&peer,
        len);
        if(n < 0)
        {
            LOG((int)LogLevel::FATAL) << "发送信息失败，客服端退出!";
            exit(1);
        }
        LOG((int)LogLevel::FATAL) << "消息发送成功!";


        char rcMessage[1000];
        n = recvfrom(sockfd, rcMessage, sizeof(rcMessage), 0, (sockaddr*)&peer, &len);
        if(n < 0)
        {
            LOG((int)LogLevel::FATAL) << "接收信息失败，客服端退出!";
            exit(1);
        }
        //LOG((int)LogLevel::FATAL) << "接收信息成功!";
        LOG((int)LogLevel::FATAL) << rcMessage;
    }
    
    return 0;
}